//
// File:        rm_rid.cc
// Description: RM_Manager class implementation
// Authors:     Haris Wang (dynmiw@gmail.com)
//
// 
#include <cstdio>
#include <unistd.h>
#include <iostream>
#include "rm.h"

//
// CreateFile
// 
// Desc: Create a new RM table/file named fileName with recordSize as the fixed size of records.
// In:  fileName - name of file to create
// In:  recordSize
// Ret: RM return code
// 
RC RM_Manager::CreateFile (const char *fileName, int recordSize)
{
    if ( recordSize > PF_PAGE_SIZE )
    {
        return 1;
    }
    

}

//
// DestoryFile
//
// Desc: Delete a RM file named fileName
// In:   filename - name of file to delete
// Ret:  RM return code
//
RC RM_Manager::DestroyFile(const char *fileName)
{
    RC rc = pfm.DestroyFile(fileName);
    if( rc<0 )
    {
        PF_PrintError(rc);
        return (START_RM_ERR - 1);
    }

    return 0;
}

//
// OpenFile
//
// Desc: Open a RM file named fileName; Modify local var's in fileHandle
//       to point to the file data in the table, and to point to the buffer 
//       manager object
// In:   fileName  
// Out:  fileHandle - refer to the open file
// Ret:  RM return code
RC RM_Manager::OpenFile   (const char *fileName, RM_FileHandle &fileHandle)
{
    PF_FileHandle pfh;
    RC rc = pfm.OpenFile(fileName, pfh);
    if(rc<0)
    {
        PF_PrintError(rc);
        return (START_RM_ERR - 1);
    }


}

//
// CloseFile
//
// Desc: Close file associated with fileHandle
// In:   fileHandle - handle of file to close
// Out:  fileHandle - no longer refers to an open file
// Ret:  RM return code
//
RC RM_Manager::CloseFile  (RM_FileHandle &fileHandle)
{
    if(!fileHandle.bFileOpen || fileHandle.pfHandle == NULL)
        return (START_RM_ERR - 6);
    
    RC rc;
    if(fileHandle.hdrChanged())
    {
        // write header to disk
        PF_PageHandle ph;
        fileHandle.pfHandle->GetThisPage(0, ph);
        fileHandle.SetFileHeader(ph); // write hdr into file

        rc = fileHandle.pfHandle->MarkDirty(0);
        if (rc < 0)
        {
        PF_PrintError(rc);
        return rc;
        }

        rc = fileHandle.pfHandle->UnpinPage(0);
        if (rc < 0)
        {
        PF_PrintError(rc);
        return rc;
        }

        rc = fileHandle.ForcePages();
        if (rc < 0)
        {
        RM_PrintError(rc);
        return rc;
        }
    }

    rc = pfm.CloseFile(*fileHandle.pfHandle);
    if(rc<0)
    {
        PF_PrintError(rc);
        return rc;
    }

    delete fileHandle.pfHandle;
    fileHandle.pfHandle = NULL;
    fileHandle.bFileOpen = false;

    return 0;
}
